<template>
    <div class="template-panel">
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索"
          size="small"
        ></el-input>
        <div class="search-icon">
          <i class="el-icon-search"></i>
        </div>
      </div>
      <div class="divider"></div>
      <div class="content">
        <div class="color-section">
          <div class="color-boxes">
            <div class="color-picker">
              <el-color-picker v-model="selectedColor" size="small" @change="updateBoardBackground"></el-color-picker>
            </div>
            <div 
              v-for="(color, index) in colorList" 
              :key="index"
              class="color-box"
              :style="{ backgroundColor: color }"
              @click="handleColorClick(color)"
            ></div>
          </div>
        </div>
        <div class="waterfall-section">
          <div class="waterfall-container">
            <div 
              v-for="(item, index) in waterfallItems" 
              :key="index"
              class="waterfall-item"
              :style="{ 
                height: item.height + 'px',
                background: item.gradient
              }"
              @click="applyGradientToBoard(item.gradient)"
            ></div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    name: 'TemplatePanel',
    data() {
      return {
        searchText: '',
        selectedColor: '#409EFF',
        colorList: [
          '#409EFF',
          '#67C23A',
          '#E6A23C',
          '#F56C6C',
          '#909399',
          '#000000',
          '#FFFFFF',
          '#FF0000',
          '#00FF00'
        ],
        waterfallItems: [],
        konva: this.konvaStage
      };
    },
    inject: ['konvaStage'],
    created() {
      this.initWaterfallItems();
    },
    methods: {
      initWaterfallItems() {
        this.waterfallItems = Array.from({ length: 20 }, () => ({
          height: Math.floor(Math.random() * 100) + 100, // 100-200px 的随机高度
          gradient: this.generateGradient()
        }));
      },
      handleColorClick(color) {
        const KonvaInstance = this.konva;
        const { stage } = KonvaInstance.stage;
        const boardNode = stage.findOne('.board');
        boardNode.setAttr('fill', color); // 直接设置新颜色
        stage.batchDraw(); // 强制重绘画布

        // this.selectedColor = color;
        this.updateBoardBackground(color);
      },
      generateGradient() {
        const colors = [
          ['#FF3CAC', '#784BA0', '#2B86C5'],
          ['#FF9A8B', '#FF6A88', '#FF99AC'],
          ['#00C9FF', '#92FE9D'],
          ['#F6D365', '#FDA085'],
          ['#84FAB0', '#8FD3F4'],
          ['#A9C9FF', '#FFBBEC'],
          ['#FFDEE9', '#B5FFFC'],
          ['#FF9A9E', '#FECFEF'],
          ['#FFE53B', '#FF2525'],
          ['#21D4FD', '#B721FF']
        ];
        const [color1, color2, color3] = colors[Math.floor(Math.random() * colors.length)];
        if (color3) {
          return `linear-gradient(135deg, ${color1}, ${color2}, ${color3})`;
        }
        return `linear-gradient(135deg, ${color1}, ${color2})`;
      },
      updateBoardBackground(color) {
        // 获取根组件
        const rootComponent = this.$root;
        // 获取高级编辑器组件
        if (rootComponent.$children && rootComponent.$children.length > 0) {
          const advancedComponent = rootComponent.$children.find(child => child.$options.name === 'AdvancedEditor');
          if (advancedComponent && advancedComponent.state && advancedComponent.state.konva) {
            const { stage } = advancedComponent.state.konva;
            if (stage) {
              const boardNode = stage.findOne('.board');
              if (boardNode) {
                boardNode.fill(color);
                advancedComponent.state.konva.layer.batchDraw();
              }
            }
          }
        }
      },
      applyGradientToBoard(gradient) {
        const KonvaInstance = this.konvaStage;
        if (!KonvaInstance || !KonvaInstance.stage) return;
        
        const stage = KonvaInstance.stage;
        
        // 获取节点并检查空值
        const boardNode = stage.findOne('.board');
        if (!boardNode) return;
        
        // 查找并清除可能存在的背景图片
        const bgImage = stage.findOne('#imageid');
        if (bgImage) bgImage.destroy();
        
        // 解析渐变字符串获取颜色
        const gradientStr = gradient;
        const colorMatch = gradientStr.match(/linear-gradient\(135deg,\s*([^,]+),\s*([^,]+)(?:,\s*([^)]+))?\)/);
        
        if (colorMatch) {
          const color1 = colorMatch[1].trim();
          const color2 = colorMatch[2].trim();
          const color3 = colorMatch[3] ? colorMatch[3].trim() : null;
          
          // 为画板创建渐变背景
          boardNode.fillLinearGradientStartPoint({ x: 0, y: 0 });
          boardNode.fillLinearGradientEndPoint({ x: boardNode.width(), y: boardNode.height() });
          
          if (color3) {
            boardNode.fillLinearGradientColorStops([
              0, color1,
              0.5, color2,
              1, color3
            ]);
          } else {
            boardNode.fillLinearGradientColorStops([
              0, color1,
              1, color2
            ]);
          }
          
          // 重绘画布
          stage.batchDraw();
        }
      }
    }
  };
  </script>
  
  <style lang="scss" scoped>
  .template-panel {
  
    padding: 20px 15px;
    
    .search-box {
      position: relative;
      width: 100%;
      margin-bottom: 15px;
      
      :deep(.el-input) {
        width: 100%;
        
        .el-input__inner {
          height: 32px;
          line-height: 32px;
          border-radius: 4px;
          padding-left: 12px;
          padding-right: 40px;
          font-size: 14px;
        }
      }
      
      .search-icon {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        display: flex;
        align-items: center;
        justify-content: center;
        width: 16px;
        height: 16px;
        cursor: pointer;
        
        i {
          font-size: 14px;
          color: #909399;
        }
        
        &:hover {
          i {
            color: #409eff;
          }
        }
      }
    }
  
    .divider {
      width: 100%;
      height: 1px;
      background-color: #dcdfe6;
      margin-bottom: 15px;
    }
    
    .content {
      .color-section {
        margin-bottom: 20px;
        
        .color-boxes {
          display: grid;
          grid-template-columns: repeat(5, 50px);
          grid-template-rows: repeat(2, 50px);
          gap: 10px;
          
          .color-picker {
            :deep(.el-color-picker) {
              width: 50px;
              height: 50px;
              
              .el-color-picker__trigger {
                width: 50px;
                height: 50px;
                padding: 0;
                border: 1px solid #dcdfe6;
                border-radius: 4px;
              }
            }
          }
          
          .color-box {
            width: 50px;
            height: 50px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
            
            &:hover {
              transform: scale(1.05);
            }
          }
        }
      }
  
      .waterfall-section {
        margin-top: 20px;
        
        .waterfall-container {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 10px;
          max-height: 650px;
          overflow-y: auto;
          padding-right: 5px;
          padding-bottom: 20px;
          
          &::-webkit-scrollbar {
            width: 4px;
          }
          
          &::-webkit-scrollbar-thumb {
            background-color: #dcdfe6;
            border-radius: 2px;
          }
          
          .waterfall-item {
            border-radius: 4px;
            transition: all 0.3s;
            
            &:hover {
              transform: scale(1.02);
              box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            }
          }
        }
      }
    }
  }
  </style> 